//
//  MinePublishListViewController.swift
//  MT
//
//  Created by M on 2020/1/5.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
/// 网络、通用
import MTCategory
import Moya
import Result
import RxSwift
import RxCocoa
/// 其它
import YPNavigationBarTransition
import MJRefresh
import JXPagingView
import JXCategoryView
/// 视频播放
import ZFPlayer

protocol MinePublishListViewControllerDelegate: NSObjectProtocol {
    func publishViewController(_ controller: MinePublishListViewController, shouldPushToPhotoCollectionControllerWithList list: [UserMediaListModel])
}

class MinePublishListViewController: BaseViewController {
    
    /// 代理
    weak var delegate: MinePublishListViewControllerDelegate?
    
    /// MineApi
    private lazy var provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    /// PublishApi
    private lazy var publish_provider: MTProvider<PublishApi> = {
        return MTProvider<PublishApi>(plugins: [])
    }()
    
    private lazy var homeProvider: MTProvider<HomeApi> = {
           return MTProvider<HomeApi>(plugins: [])
       }()
    
    private let disposeBag = DisposeBag()
    
    /// 当前列表页数
    var curPage: Int = 1
    
    /// 列表数据
    var models: [MineInfoListModel]? {
        didSet {
            collectionView.reloadData()
        }
    }
    
    /// 是否在播放
    fileprivate var isPlaying: Bool {
        return self.player.currentPlayerManager.isPlaying ?? false
    }
    /// 播放器
    lazy var player: ZFPlayerController = {
        let manager = ZFAVPlayerManager()
        manager.isMuted = true
        manager.view.backgroundColor = .black
        let p = ZFPlayerController(scrollView: self.collectionView, playerManager: manager, containerViewTag: 8888)
        p.isWWANAutoPlay = false
        p.shouldAutoPlay = false
        p.playerDisapperaPercent = 0
        p.allowOrentitaionRotation = false
        p.gestureControl.disableTypes = ZFPlayerDisableGestureTypes.all
        p.notification.willResignActive = { [weak self] (registrar) in
            guard let weakSelf = self else { return }
            if p.isViewControllerDisappear {
                return
            }
            if p.isFullScreen && p.isLockedScreen == false {
                p.orientationObserver.isLockedScreen = true
            }
            if p.pauseWhenAppResignActive == false {
                UIApplication.shared.beginReceivingRemoteControlEvents()
                try? AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
            }
        }
        return p
    }()
    private var isNoticeLikeTip: Bool = false
    /// 是否自己
    var isSelf: Bool {
        username == nil
    }
    var username: String?

    /// 滑动回调
    var tableViewDidScrollCallBack: ((UIScrollView) -> Swift.Void)?
    
    lazy var collectionView: UICollectionView = {
        /// 设置大小
        //let inset: CGFloat = 15.0
        let itemWidth = (ScreenWidth - 4) / 2
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: 250 * ScreenWidth / 375)
        flowLayout.minimumLineSpacing = 3
        flowLayout.minimumInteritemSpacing = 3
        let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: MiTuGiftView.collectionViewHeight), collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.common.x161616
        
        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
        
        cv.showsHorizontalScrollIndicator = false
        /// 注册 Cell
        cv.register(MTMinePblishCollectionViewCell.self, forCellWithReuseIdentifier: MTMinePblishCollectionViewCell.reuseIdentity())
        cv.emptySetView = ViewFactory.emptySetView { [weak self] in
            guard let weakself = self else { return }
           
        }
        return cv
    }()
    
}

extension MinePublishListViewController: UICollectionViewDelegate, UICollectionViewDataSource, MTMinePblishCollectionViewCellDelegate {
    //MARK: UICollectionViewDataSource
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // TODO:- Required Method
        return models?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MTMinePblishCollectionViewCell.reuseIdentity(), for: indexPath) as! MTMinePblishCollectionViewCell
        configureCell(cell: cell, forItemAt: indexPath)
        // TODO:- Required Method
        cell.delegate = self
        return cell
    }
    
    func configureCell(cell: MTMinePblishCollectionViewCell, forItemAt indexPath: IndexPath) {
        if let model = self.models?[indexPath.item] {
            cell.model = model
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let list = self.models?[indexPath.item].imgList, list.first?.objType != 1 {
            delegate?.publishViewController(self, shouldPushToPhotoCollectionControllerWithList: list)
        } else {
            /// 是视频
            if let model = self.models?[indexPath.item] {
                let vc = MTMineSingleVideoPlayerController()
                vc.model = model
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    
    func likeEvent(cell: MTMinePblishCollectionViewCell, goodButton: GKLikeView, model: MineInfoListModel?, countLabel: UILabel) {
//        if !isNoticeLikeTip {
//            UIAlertController.rx.show(in: self, title: "提示", message: "点赞需要消耗1钻石", buttons: [.cancel("取消"), .default("确定")]).subscribe(onSuccess: { [weak self] index in
//                guard let weakSelf = self else { return }
//                /// 去充值的引导
//                if index == 1 {
//                    weakSelf.isNoticeLikeTip = true
//                    weakSelf.privateLikeEvent(cell: cell, goodButton: goodButton, model: model, countLabel: countLabel)
//                }
//            })
//            .disposed(by: globalDisposedBag)
//            isNoticeLikeTip = true
//            return
//        }
//        
//        privateLikeEvent(cell: cell, goodButton: goodButton, model: model, countLabel: countLabel)
        
    }
        
    private func privateLikeEvent(cell: MTMinePblishCollectionViewCell, goodButton: GKLikeView, model: MineInfoListModel?, countLabel: UILabel) {
//        guard let trendId = model?.lastTrendId else { return }
//        provider.rx.requestResult(.realTrendsLike(trendId: trendId)).subscribe(onNext: { (result:Result<HomeLikeComponentModel, AnyError> , isCache:Bool) in
//            switch result {
//            case .success(let listModel):
//                if listModel.code == 200 {
//                    DispatchQueue.main.async {
//                        model?.selfLike = 1
//                        goodButton.setupLikeCount("\(listModel.result)")
//                        goodButton.startAnimation(withIsLike: true, canHit: true)
//                    }
//                }
//                /// 用户余额不足
//                if listModel.code == 600 {
//                    UIAlertController.rx.show(in: self, title: "提示", message: "点赞需要消耗1钻石，钻石不足，请充值", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
//                        /// 去充值的引导
//                        if index == 1 {
//                            if UserDefaults.AppValidate.isValidate.storedBool == false {
//                                let c = MTPaymentViewController()
//                                self.navigationController?.pushViewController(c, animated: true)
//                            } else {
//                                let c = MTInAppPurchasesViewController()
//                                self.navigationController?.pushViewController(c, animated: true)
//                            }
//                        }
//                    })
//                    .disposed(by: globalDisposedBag)
//                }
//            case .failure(_):
//                break
//            }
//            
//        }).disposed(by: globalDisposedBag)
    }
    
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MinePublishListViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeUI()
        requestUserInfoList()
        if #available(iOS 11,*) {
            collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.play()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.pause()
    }
}

// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MinePublishListViewController {
    
    private func initializeUI() {
        view.backgroundColor = .black
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        player.playerDidToEnd = { [weak self] (asset) in
            guard let weakself = self else { return }
            weakself.player.currentPlayerManager.replay?()
        }
    }
    
}

// MARK: ------------------------------------ 数据请求 ----------------------------------------
extension MinePublishListViewController {
    
    public func reloadList(group: DispatchGroup? = nil) {
        curPage = 1
        models?.removeAll()
        requestUserInfoList(isAppending: false, withGroup: group)
    }
    
    /// 获取用户发布列表
    private func requestUserInfoList(isAppending: Bool = false, withGroup group: DispatchGroup? = nil) {
        group?.enter()
        provider.rx.requestResult(.list(curPage, username)).subscribe(onNext: { [weak self] (result: Result<MineInfoListResponseModel, AnyError>, isCache: Bool) in
            guard let weakSelf = self else {
                group?.leave()
                return
            }
            weakSelf.collectionView.mj_footer?.endRefreshing()
            switch result {
            case let .success(response):
                if let code = response.code, code == 200 {
                    if let result = response.result, result.count > 0 {
                        weakSelf.curPage += 1
                        if isAppending {
                            weakSelf.models?.append(contentsOf: result)
                        } else {
                            weakSelf.models = result
                            /// 默认播放第一个视频 - 取消
                            //weakSelf.playVideo(at: IndexPath(row: 0, section: 0), scrollToTop: false)
                        }
                    }
                }
                break
            case .failure(_):
                break
            }
            group?.leave()
        }).disposed(by: disposeBag)
    }
        
        /// 删除帖子请求
    private func removePost(model: MineInfoListModel) {
        guard let id = model.id else { return }
        publish_provider.originRequest(.delete(id: id), callbackQueue: .main, progress: nil) { [weak self] (result, _) in
            guard let weakself = self else { return }
            switch result {
                
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int, code == 200 {
                    /// 删除成功
                    AlertManager.presentAlertView(message: "删除成功")
                    if let models = weakself.models, let idx = models.firstIndex(where: { (m) -> Bool in
                        return m.id == model.id
                    }) {
                        weakself.models?.remove(at: idx)
                        weakself.collectionView.reloadData()
                    }
                } else {
                    /// 删除失败
                    AlertManager.presentAlertView(message: "删除成功")
                }
                break
            case .failure(_):
                /// 删除失败
                AlertManager.presentAlertView(message: "删除成功")
                break
            }
        }
    }
    
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MinePublishListViewController {
    
    private func loadMoreData() {
        requestUserInfoList(isAppending: true)
    }
    
}

// MARK: ------------------------------------ 视频播放相关 ----------------------------------------
extension MinePublishListViewController {
    
    /// 根据 IndexPath 播放内容
    private func playVideo(at indexPath: IndexPath, scrollToTop: Bool) {
        guard let model = models?[indexPath.row] else { return }
        if model.imgList?.first?.objType == 1, let href = model.imgList?.first?.href, let url = URL(string: href) {
            if self.player.playingIndexPath != indexPath {
                try? AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
                self.player.playTheIndexPath(IndexPath(row: 0, section: 0), assetURL: url, scrollToTop: false)
            }
        } else {
            self.player.stopCurrentPlayingCell()
            try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
        }
    }
    
    /// 播放
    public func play() {
        if isPlaying { return }
        self.player.currentPlayerManager.play?()
    }
    
    /// 暂停
    public func pause() {
        if !isPlaying { return }
        self.player.currentPlayerManager.pause?()
    }
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ JXPagingViewListViewDelegate ----------------------
extension MinePublishListViewController: JXPagingViewListViewDelegate {
    
    func listView() -> UIView {
        view
    }
    
    func listScrollView() -> UIScrollView {
        collectionView
    }
    
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        tableViewDidScrollCallBack = callback
    }
 
    func listDidAppear() {
        self.play()
    }
    
    func listDidDisappear() {
        self.pause()
    }
    
}

// MARK: ------------------ UITableViewDelegate ----------------------
extension MinePublishListViewController: UITableViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidEndDecelerating()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        scrollView.zf_scrollViewDidEndDraggingWillDecelerate(decelerate)
    }
    
    func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScrollToTop()
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewWillBeginDragging()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if let callback = tableViewDidScrollCallBack {
            callback(scrollView)
        }
        scrollView.zf_scrollViewDidScroll()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
    }
    
}

//// MARK: ------------------ MineTimelineTableViewCellDelegate ----------------------
//extension MinePublishListViewController: MineTimelineTableViewCellDelegate {
//
//    func timelineCell(_ cell: MineTimelineTableViewCell, didClickRemoveButtonWithModel model: MineInfoListModel) {
//        let c = UIAlertController(title: "是否删除帖子", message: nil, preferredStyle: .alert)
//        let a1 = UIAlertAction(title: "确定", style: .default) { (action) in
//            self.removePost(model: model)
//        }
//        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
//        c.addAction(a1)
//        c.addAction(cancel)
//        present(c, animated: true, completion: nil)
//    }
//
//    func timelineCell(_ cell: MineTimelineTableViewCell, didClickExpandButtonWithModel model: MineInfoListModel) {
//        model.isExpanded = !model.isExpanded
//        self.collectionView.reloadData()
//    }
//
//    func timelineCell(_ cell: MineTimelineTableViewCell, didSelectPhotoCollectionWithImageList list: [UserMediaListModel]) {
//        if let delegate = delegate, list.first?.objType != 1 {
//            delegate.publishViewController(self, shouldPushToPhotoCollectionControllerWithList: list)
//        }
//    }
//
//    func timelineCell(_ cell: MineTimelineTableViewCell, didClickPlayPauseButton isPlay: Bool) {
//        isPlay ? self.play() : self.pause()
//    }
//
//}
